/*******************************************************************************
 * Copyright (c) 2011 Grupo de Sistemas Inteligentes (GSI) - DIT UPM
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package es.upm.dit.gsi.eclipse.jadex.adfmanager.wizards;


import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.dialogs.ResourceSelectionDialog;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

import es.upm.dit.gsi.jadex.customproject.natures.JadexProjectNature;

/**
 * This page allows to get the following information in order to log into the repository 
 *  -User
 *  -Password
 *    
 *  @author Mario Moreno
 */

public class ImportCapabilityWizardPage extends WizardPage {
	private Text capabilityFileText;
	private Table filesTable;
	private ArrayList<IFile> fileList;
	private Text projectText;
	private Button browseButton;
	private IProject selectedProject;
	
	/**
	 * Constructor for LoginRepositoryWizardPage
	 * 
	 * @param pageName
	 */
	public ImportCapabilityWizardPage() {
		super("wizardPage");
		setTitle("Export to Repository");
		setDescription("This wizard exports the selected capability to the repository");
	}

	/**
	 * @see IDialogPage#createControl(Composite)
	 */
	public void createControl(Composite parent) {		
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 3;
		layout.verticalSpacing = 9;
		PlatformUI.getWorkbench().getHelpSystem().setHelp(container, "es.upm.dit.gsi.eclipse.jadex.adfmanager.addExpressionWizard");
		
		GridData gd1 = new GridData(SWT.FILL, SWT.TOP, true, false,1,1);
		GridData gd3 = new GridData(SWT.FILL, SWT.TOP, true, false,3,1);
		
		Label label1 = new Label(container, SWT.NULL);
		label1.setText("Destination project: ");
		projectText = new Text(container, SWT.BORDER | SWT.SINGLE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		projectText.setLayoutData(gd);
		projectText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
		projectText.setToolTipText("Click on browse to select a project");
		projectText.setEditable(false);
		browseButton = new Button(container, SWT.PUSH);
		browseButton.setText("Browse...");
		browseButton.addSelectionListener(new SelectionAdapter(){
			public void widgetSelected(SelectionEvent e) {
				handleBrowse();
			}
		});
		
		Label separator = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		separator.setLayoutData(gd);
		gd.horizontalSpan = 3;	
		
		Label label2 = new Label(container, SWT.NULL);
		label2.setText("List of capabilities from the server: ");
		filesTable = new Table (container, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
		filesTable.setLinesVisible (true);
		filesTable.setHeaderVisible (false);
		GridData gd2 = gd3;
		gd2.heightHint = 230;
		filesTable.setLayoutData(gd2);
		TableColumn column = new TableColumn(filesTable,SWT.NONE);
		column.setText("files");
		column.pack();
		
		initialize();
		dialogChanged();
		setControl(container);
	}
	
	private void handleBrowse() {		
		ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
			    getShell(), new WorkbenchLabelProvider(), new BaseWorkbenchContentProvider());
			dialog.setTitle("Select target Project");
			dialog.setMessage("Select the target project for the new capabilites:");
			dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
			dialog.setAllowMultiple(false);
			dialog.addFilter(new ViewerFilter() {				
				@Override
				public boolean select(Viewer viewer, Object parentElement, Object element) {
					if(element instanceof IProject){
						IProject p = (IProject) element;
						try{
							if(p.hasNature(JadexProjectNature.NATURE_ID)){
								return true;
							}
						}
						catch(CoreException e1){
							return false;
						}		
					}
					return false;
				}
			});		
		if (dialog.open() == ResourceSelectionDialog.OK) {
			Object[] result = dialog.getResult();
			IProject p = (IProject) result[0];
			projectText.setText(p.getName());
			selectedProject = p;
			dialogChanged();
		}
	}

	/**
	 * Tests if the current workbench selection is a suitable container to use.
	 */
	private void initialize() {
	}

	/**
	 * Ensures that the all text fields are set correctly.
	 */
	private void dialogChanged() {
		updateStatus(null);
	}

	/*
	 * This method is called in order to update the status message 
	 */
	private void updateStatus(String message) {
		setErrorMessage(message);
		setPageComplete(message == null);
	}	
	
	private void updateFileList() throws SAXException, IOException, ParserConfigurationException{
		IFile capabilityFile = fileList.get(0);
			
		if(capabilityFile == null | !capabilityFile.exists()){
			return;
		}
		if(capabilityFileText.getText().length() <= 0){
			return;
		}
		IProject project = capabilityFile.getProject();
		
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(capabilityFile.getRawLocation().toOSString());
	 
		NodeList plans = doc.getElementsByTagName("plan");		
		
		for(int i = 0; i < plans.getLength() ; i++){
			IFile resource = null;
			Element plan = (Element) plans.item(i);
			Element body = (Element) plan.getElementsByTagName("body").item(0);
			if(body != null){
				String classname = ((Element)body).getAttribute("class");
				System.out.println(classname);
				if(classname != null & classname.length() > 0){
					resource = project.getFile(((Element)body).getAttribute("class")+".java");
					System.out.println(resource.getName());
				}
				
			}
			if(resource != null ){
				fileList.add(resource);				
			}	
		}
		
		for(IFile f : fileList){
			TableItem item  = new TableItem(filesTable, SWT.NONE);
			item.setText(f.getProjectRelativePath().toOSString());
		}

	}
	
	/**
	 * 
	 * @return the destination project for the new agent
	 */
	public IProject getSelectedProject(){
		return selectedProject;
	}
	
	
	
	
}